import { user } from '@/store';
import { storeToRefs } from 'pinia';
import { getCache } from '@/utils';

const CONFIG = {
    host: import.meta.env.VITE_HOST || '',
    baseURL: '/api/main',
    // baseURL: '',
    timeout: 60000,
    method: 'GET',
};

export class HttpError extends Error {
    data: any;
    constructor(message: string, data: Record<string, any>) {
        super(message);
        this.data = data;
    }
}

const request = async (config: Record<string, any>): Promise<any> => {
    const networkType = await uni.getNetworkType();
    if (networkType.networkType === 'none') {
        uni.showModal({
            content: '暂无网络，请恢复网络后使用',
            confirmText: '知道了',
            showCancel: false,
            confirmColor: '#ffe60f',
        });
        return Promise.reject(
            new HttpError('暂无网络，请恢复网络后使用', {
                code: '-1',
            }),
        );
    }
    return new Promise((resolve, reject) => {
        const { clear } = user();
        const { token } = storeToRefs(user());
        const mergerToken = token.value || getCache('token');
        const method = (config.method || CONFIG.method).toUpperCase();
        console.log('data',config)
        uni.request({
            method,
            url: (config.host || CONFIG.host) + (config.baseURL || CONFIG.baseURL) + config.url,
            data: method === 'GET' ? config.params : config.data,
            timeout: config.timeout || CONFIG.timeout,
            header: {
                Authorization: mergerToken ? `Bearer ${mergerToken}` : '',
                ...config.headers,
            },
            complete(res: anyObj) {
                
                if (res.statusCode === 200) {
                    if (res.data.code === 200) {
                        return resolve(res.data);
                    } else {
                        if (!config.showToast) {
                            uni.showToast({
                                title: res.data?.message,
                                icon: 'none',
                                duration: 3000,
                            });
                        }
                        return reject(new HttpError(res.data?.message, res.data));
                    }
                } else {
                    res.href = (config.baseURL || CONFIG.baseURL) + config.url;
                    if (res.statusCode === 401) {
                        clear();

                        uni.reLaunch({
                            url: '/pages/login/index',
                        });
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title:
                                res.statusCode === 500
                                    ? '服务异常'
                                    : res?.data?.message || '服务异常，请稍后重试',
                        });
                    }
                    return reject(
                        new HttpError(res.data?.message, {
                            code: res.statusCode,
                            data: res.data,
                        }),
                    );
                }
            },
        });
    });
};

export default request;
